#include "work_channel_manager.h"

namespace dl {

// WorkChannelManager
WorkChannelManager::WorkChannelManager(MessageLoop* message_loop, 
    MessageTransfer* message_transfer, base::Closure exit_callback) {
  DetachFromThread();
  message_loop_      = message_loop;
  message_transfer_  = message_transfer;
  exit_callback_     = exit_callback;
}

WorkChannelManager::~WorkChannelManager() {
}

// Called on the main ui thread
void WorkChannelManager::CreateChannel(const std::string& name) {
  if (name.empty()) return;
  WorkChannel* channel = new WorkChannel(name, message_loop_, this, message_transfer_);
}

void WorkChannelManager::OnConnectArrived(WorkChannel* channel, int32 peer_pid) {
  DCHECK(CalledOnValidThread());
  DCHECK(channel);
  ChannelMap::iterator iter = render_hosts_.find(channel->PeerProcessID());
  if (iter == render_hosts_.end()) {
    render_hosts_[channel->PeerProcessID()] = channel;
  }
}

void WorkChannelManager::OnConnectError(WorkChannel* channel) {
  DCHECK(CalledOnValidThread());
  DCHECK(channel);
  ChannelMap::iterator iter = render_hosts_.find(channel->PeerProcessID());
  if (iter != render_hosts_.end()) {
    render_hosts_.erase(iter);
    if (render_hosts_.empty()) exit_callback_.Run();
  }
  delete channel;
}


}
